package com.cn.kehong.service;

import com.cn.kehong.api.IDataSubmissionScService;
import com.cn.kehong.dao.DataSubmissionScMapper;
import com.cn.kehong.domain.DataSubmissionSc;
import com.cn.kehong.domain.DataSubmissionScExample;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DataSubmissionScServiceImpl implements IDataSubmissionScService {

    @Autowired
    private DataSubmissionScMapper dataSubmissionScMapper;

    @Override
    public List<DataSubmissionSc> getDataSubmissionScListById(String submissionId) throws Exception {
        if(StringUtils.isEmpty(submissionId)){
            return Lists.newArrayList();
        }
        DataSubmissionScExample example = new DataSubmissionScExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andSubmissionIdEqualTo(submissionId);
        example.setOrderByClause("sort_index asc");
        List<DataSubmissionSc> list = dataSubmissionScMapper.selectByExample(example);
        return list;
    }

    @Override
    public String addDataSubmissionSc(List<DataSubmissionSc> dataSubmissionScs) throws Exception {
        if(CollectionUtils.isEmpty(dataSubmissionScs)){
            return "数组为空！";
        }
        int count = dataSubmissionScMapper.batchInsertDataSubmissionSc(dataSubmissionScs);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateDataSubmissionSc(List<DataSubmissionSc> dataSubmissionScs) throws Exception {
        if(CollectionUtils.isEmpty(dataSubmissionScs)){
            return "数组为空！";
        }
        String submissionId = dataSubmissionScs.get(0).getSubmissionId();
        if(StringUtils.isEmpty(submissionId)){
            return "id 为空！";
        }
        DataSubmissionScExample example = new DataSubmissionScExample();
        example.createCriteria().andSubmissionIdEqualTo(submissionId);
        int count = dataSubmissionScMapper.deleteByExample(example);
        if(count < 0){
            return "清理数据异常！";
        }
        count = dataSubmissionScMapper.batchInsertDataSubmissionSc(dataSubmissionScs);
        if(count < 1){
            throw new Exception("插入数据异常！");
        }
        return "";
    }
}
